package com.sctvcloud.qingchuan.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.base.BaseActivity;
import com.sctvcloud.qingchuan.beans.FocusColumn;
import com.sctvcloud.qingchuan.beans.HomeEvent;
import com.sctvcloud.qingchuan.beans.PoliticsScreenCondition;
import com.sctvcloud.qingchuan.ui.activities.LoginActivity;
import com.sctvcloud.qingchuan.ui.activities.PoliticsCommitActivity;
import com.sctvcloud.qingchuan.ui.activities.ScreenConditionActivity;
import com.sctvcloud.qingchuan.ui.adapter.PoliticsFormPageAdapter;
import com.sctvcloud.qingchuan.ui.adapter.PoliticsListAdapter;
import com.sctvcloud.qingchuan.ui.fragment.ColumnBaseFragment;
import com.sctvcloud.qingchuan.ui.fragment.PoliticsListFragment;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 问政
 */
public class PoliticsFragment extends ColumnBaseFragment {

    @BindView(R.id.home_tablay)
    protected SlidingTabLayout home_tablay;
    @BindView(R.id.home_content_vp)
    protected ViewPager home_content_vp;

    @BindView(R.id.home_top_lay_tab)
    protected ViewGroup tabLay;
    @BindView(R.id.input_screen_key)
    protected CustomFontEditText editSearch;
    @BindView(R.id.home_content_ll)
    protected LinearLayout content_ll;
    private PoliticsFormPageAdapter homePagerAdapter;
    private ArrayList<FocusColumn> list = new ArrayList<FocusColumn>();
    public static final int REQUEST_CODE = 1;
    private static final String IS_START = "IS_START";
    public static final String NET_TAG = "chooseCityFuncFragment";


    protected static final int CODE_REQUEST_LOGIN = 303;
    protected static final int SCREEN_CONDITION = 1;//选择筛选条件

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_politics_list, container, false);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_politics, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        editSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(editSearch.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //搜索
                    refreshPoliticsData();
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = editSearch.getText().toString().trim();
                PoliticsScreenCondition condition = Cache.getInstance().getPcCondition();
                if (null == condition) {
                    condition = new PoliticsScreenCondition();
                }
                condition.setInputKey(key);
                Cache.getInstance().setPcCondition(condition);
            }
        });
        tabLay.setFocusable(true);
        tabLay.setFocusableInTouchMode(true);
        tabLay.requestFocus();
        initData();
    }


    @Override
    public void onDestroyView() {
        Cache.getInstance().setPcCondition(null);
        super.onDestroyView();
    }


    @Override
    public void onResume() {
        super.onResume();
        Cache.getInstance().setCurrentChannelId(Cache.getInstance().getCurrentColumnId("问政", "回音壁"));
    }


    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    private void initData() {

        FocusColumn news = new FocusColumn();
        news.setChannelName("最新发布");
        news.setChannelType(String.valueOf(PoliticsFormPageAdapter.TYPE_NEW_PUBLISH));

//        FocusColumn hots = new FocusColumn();
//        hots.setChannelName("最热问政");
//        hots.setChannelType(String.valueOf(PoliticsFormPageAdapter.TYPE_HOTS_POLITICS));

        list.add(news);
//        list.add(hots);

        setData(list);
    }

    /**
     * 加载 首页中的各个栏目页面
     *
     * @param fChannels
     */
    private void setData(List<FocusColumn> fChannels) {
        if (ListUtils.isListValued(fChannels)) {
            content_ll.setVisibility(View.VISIBLE);

            boolean b = true;
            int s = -1;
            if (homePagerAdapter == null) {
                homePagerAdapter = new PoliticsFormPageAdapter(getChildFragmentManager(), list);
                setAdapterTopHeiht(true);
                home_content_vp.setAdapter(homePagerAdapter);
                home_content_vp.setOffscreenPageLimit(1);
                home_content_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageSelected(int position) {
                        int count = homePagerAdapter.getCount();
                        for (int i = 0; i < count; i++) {
                            ColumnBaseFragment fragment = homePagerAdapter.getFragmentByPos(i);
                            if (position == i) {
                                fragment.onHiddenChanged(false);
                            } else {
                                fragment.onHiddenChanged(true);
                            }
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
                home_tablay.setViewPager(home_content_vp);
                s = homePagerAdapter.getCount();
            } else {
                s = homePagerAdapter.getCount();
                setAdapterTopHeiht(true);
                homePagerAdapter.setData(list);
                b = s != homePagerAdapter.getCount();
            }
//            home_tablay.setOnTabSelectListener(this);
//            refreshColumnTab(b);

        } else {
            content_ll.setVisibility(View.GONE);
        }
        home_tablay.setChangeSize(true);
        home_tablay.notifyDataSetChanged();
        home_tablay.setTabPadding(0);
        home_tablay.setTabSpaceEqual(true);
    }

    /**
     * 获取当前正显示的Fragment
     *
     * @return
     */
    public ColumnBaseFragment getCurrentFragment() {
        if (home_content_vp == null || homePagerAdapter == null || homePagerAdapter.getCount() == 0) {
            return null;
        }
        ColumnBaseFragment cbf = homePagerAdapter.getFragmentByPos(home_content_vp.getCurrentItem());
        JLog.e("ffsf " + cbf);

        return cbf;
    }


//    /**
//     * 刷新栏目在首页的标签
//     *
//     * @param b
//     */
//    private void refreshColumnTab(boolean b) {
//        int size = homePagerAdapter.getCount();
//        if (size == 0 || !b) {
//            return;
//        }
//    }


    @OnClick({R.id.screen_condition, R.id.iv_add})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.screen_condition:
                Intent intent = new Intent(getContext(), ScreenConditionActivity.class);
                startActivityForResult(intent, SCREEN_CONDITION);
                break;
            case R.id.iv_add:
                if (UserManager.getInstance().isLogin()) {
                    Intent intent1 = new Intent(getContext(), PoliticsCommitActivity.class);
                    startActivity(intent1);
                } else {
                    toLogin();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CODE_REQUEST_LOGIN) {
                home_content_vp.setCurrentItem(0);
            } else if (requestCode == SCREEN_CONDITION) {
                refreshPoliticsData();
            }

        }
    }

    /**
     * 变更了筛选条件，刷新数据
     */
    private void refreshPoliticsData() {
        PoliticsListFragment fragment = (PoliticsListFragment) homePagerAdapter.getFragmentByPos(home_tablay.getCurrentTab());
        if (null != fragment) {
            fragment.refreshScreenData();
        }
    }


    private void setAdapterTopHeiht(boolean isNewInstance) {
        if (isNewInstance) {
            homePagerAdapter.setTopHeight(tabLay.getHeight());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onjump(HomeEvent messageEvent) {
        if (null != messageEvent) {
            if (messageEvent.getPosition() == 0) {
                home_content_vp.setCurrentItem(0);
            } else if (messageEvent.getPosition() == 1) {
                home_content_vp.setCurrentItem(1);
            }
        }

    }

}
